# -*- coding: utf-8 -*-
"""
Mercurial processor.
"""
from processors.single_repository_processor import SingleRepositoryProcessor
from mercurial import ui, hg
from datetime import datetime
from processors.changeinfo import ChangeInfo
from myutil import myutil
    
class LocalMercurialRepoProcessor(SingleRepositoryProcessor):
    """
    Processor for local mercurial repository.
    """
    _ui = None
    _repo = None
    
    def initialize(self):
        """
        Initializes the repository.
        """
        self._ui = ui.ui()
        self._repo = hg.repository(self._ui, self.location)

    def _gather_log_info(self):
        """
        Gather information from the repository about the changes.
        """
        copy_ctx = [self._repo[i] for i in self._repo]
        for i in copy_ctx:
            date = datetime.fromtimestamp(i.date()[0])
            email = myutil.get_mail(self.settings, i.user())
            files = ", ".join(i.files())
            link = None
            if self.weburl is not None:
                if self.flavor == "cgiweb":
                    link = self.weburl + "rev/" + i.hex()
                elif self.flavor == "rhodecode":
                    link = self.weburl + "changeset/" + i.hex()
                elif self.flavor == "googlecode":
                    link = self.weburl + "source/detail?r=" + i.hex()
            change_info = ChangeInfo(i.hex(), str(i.rev()), \
                            i.user(), email , date, \
                            files, i.description(), link)
            self._append_change_info(change_info)

class PullableMercurialRepoProcessor(LocalMercurialRepoProcessor):
    """
    Mercurial repository which is pullable.
    
    Every time we check it we also pull changes from the specified repository.
    """
    def pull(self):
        """
        Pulls changes from remote repository.
        """
        remote = hg.repository(self._ui, self.pullurl)
        return str(self._repo.pull(remote))      
